package <packageRoot>;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.fmz.dao.Connection;

public class GenericDAO<E> {

	private final EntityManager entityManager = Connection.getInstance().getEntityManager();

	public GenericDAO() {
	}

	public boolean persist(E entity) {
		boolean persist = false;
		try {
			if (entity != null) {
				entityManager.getTransaction().begin();
				entityManager.persist(entity);
				entityManager.getTransaction().commit();
				persist = true;
			}
		}
		catch (Exception e) {
			entityManager.getTransaction().rollback();
			e.printStackTrace();
		}
		return persist;
	}

	public boolean merge(E entity) throws Exception {
		boolean merge = false;
		try {
			if (entity != null) {
				entityManager.getTransaction().begin();
				entityManager.merge(entity);
				entityManager.getTransaction().commit();
				merge = true;
			}
		}
		catch (Exception e) {
			entityManager.getTransaction().rollback();
			e.printStackTrace();
		}
		return merge;
	}

	public boolean remove(Class<E> classEntity, Object primaryKey) throws Exception {
		boolean remove = false;
		try {
			E entity = entityManager.find(classEntity, primaryKey);
			entityManager.getTransaction().begin();
			entityManager.remove(entity);
			entityManager.getTransaction().commit();
			remove = true;
		}
		catch (Exception e) {
			entityManager.getTransaction().rollback();
			e.printStackTrace();
		}
		return remove;
	}

	public E find(Class<E> classEntity, Object primaryKey) throws Exception {
		E entity = null;
		if (classEntity != null && primaryKey != null) {
			entity = entityManager.find(classEntity, primaryKey);
		}
		return entity;
	}

	@SuppressWarnings("unchecked")
	public List<E> list(Query query) throws Exception {
		List<E> entity = null;
		if (query != null) {
			entity = query.getResultList();
		}
		return entity;
	}

	public Query createQuery(String jpql) {
		Query query = null;
		if (jpql != null && !jpql.isEmpty()) {
			query = entityManager.createQuery(jpql);
		}
		return query;
	}

	public Query createNamedQuery(String nameQuery) {
		Query query = null;
		if (nameQuery != null && !nameQuery.isEmpty()) {
			query = entityManager.createNamedQuery(nameQuery);
		}
		return query;
	}
}